package com.wanxi.servlet;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ResultDTO;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
//        只要判断是否已经登录即可
//        后台应该过滤掉不需要判断登录的页面
//        静态资源文件需要放行，登录页面也需要放行
//        如果拿不到上面的资源，那么可以考虑过滤哪些接口？
//        req.setCharacterEncoding("UTF-8");
//        res.setCharacterEncoding("UTF-8");
        String path = req.getServletPath();
        if (path.startsWith("/back/")) {
            String username = (String) req.getSession().getAttribute("username");
            if (username == null) {
                res.getWriter().println(JSONObject.toJSONString(ResultDTO.getResult("未登录")));
//                res.sendRedirect("/html/login.html");
            } else {
// 放行
                chain.doFilter(req, res);

            }
        } else {
            chain.doFilter(req, res);
        }

    }
}
